import { DownOutlined } from '@ant-design/icons';
import { Button, Col, Form, Input, Row, Select, theme, Divider, Radio, Table, Space, Tag, Checkbox, Pagination, Switch, message, Modal } from 'antd';
import React, { useState, useContext, useEffect } from 'react';
import mycontext from '../../../../utils/myContext';
import http from '../../../../utils/fetchHttp';
import './index.scss'

const { Option } = Select;// ---表单的内容
let father;
let store//表格编辑对象
let promptBox, promptBoxMethod//提示框
let setListData;//表格数据渲染方法
let queryData;//查询表单数据监听
let queryAllDataList;//查询所有数据
let dataId;//删除数据公用Id
let productBrandArr//品牌数组

// 搜索表单
const AdvancedSearchForm = () => {
    const [selectArr, SetSelectArr] = useState([])
    const { token } = theme.useToken();
    const [form] = Form.useForm();
    const [expand, setExpand] = useState(false);
    const formStyle = {
        maxWidth: 'none',
        background: token.colorFillAlter,
        borderRadius: token.borderRadiusLG,
        padding: 10,
    };

    //点击重置
    const reset = () => {
        queryAllData()
    }

    // 点击筛选后的数据及请求
    const onFinish = (values) => {
        console.log('Received values of form: ', values);
        //查询指定数据
        const getAppointData = (values) => {
            console.log(values);
            values.productState = 0
            http({
                url: '/promotion/getAppointProductData',
                method: 'post',
                data: values
            }).then(res => {
                console.log(res);
                if (res.code === 200) {
                    setListData(res.data);
                    message.success('请求成功');

                }
            }).catch(() => {
                message.error('请求错误');
            })
        }
        getAppointData(values);
        queryData = getAppointData
    };

    useEffect(() => {
        queryData,
            queryAllDataList,
            queryAllData()
    }, [])

    //查询所有数据
    const queryAllData = () => {
        const id = {
            productState: 0
        }
        http({
            url: '/promotion/getAllProductData',
            method: 'post',
            data: id
        }).then((res) => {
            if (res.code === 200) {
                setListData(res.data);
                const Arr = res.data.map(item => {
                    return item.productBrand
                })
                productBrandArr = [...new Set(Arr)]
                SetSelectArr(productBrandArr)

                message.success('请求成功');
            }
        }).catch(() => {
            message.error('请求错误');
        })
    }

    queryAllDataList = queryAllData

    return (
        <Form form={form} name="advanced_search" style={formStyle} onFinish={onFinish}
            initialValues={{
                productName: '',
                productID: '',
                productBrand: ''
            }}
        >
            <Row gutter={24}>
                <Col span={8}>
                    <Form.Item
                        name='productName'
                        label='商品名称'
                        rules={[
                            {

                                message: 'Input something!',
                            },
                        ]}


                    >
                        <Input placeholder="商品名称" />
                    </Form.Item>
                </Col>
                <Col span={8}>
                    <Form.Item
                        name='productID'
                        label='商品编号'
                        rules={[
                            {

                                message: 'Input something!',
                            },
                        ]}
                    >
                        <Input placeholder="商品编号" />
                    </Form.Item>
                </Col>
                <Col span={8}>
                    <Form.Item
                        name='productBrand'//初始化动态变得数据
                        label='品牌'
                    >
                        {/* <Input placeholder="placeholder" /> */}
                        <Select >

                            {selectArr && selectArr.map(item => (
                                <Option key={item} value={item}>{item}</Option>
                            ))
                            }

                            {/* <Option for value={0}>请选择</Option>
                            <Option value={1}>1</Option> */}
                        </Select>
                    </Form.Item>
                </Col>
            </Row>
            {/* 按钮 */}
            <Row>
                <Col
                    span={24}
                    style={{
                        // textAlign: 'right',
                    }}
                >
                    <Button type="primary" htmlType="submit"
                    >
                        筛选
                    </Button>
                    <Button
                        style={{
                            margin: '0 .8rem',
                        }}
                        onClick={() => {
                            form.resetFields();
                            //发送请求
                            reset();
                        }}
                    >
                        重置
                    </Button>
                </Col>
            </Row>
        </Form>
    );
};

// 表格
const TableDetail = () => {
    const columns = [
        {
            title: '序号',
            dataIndex: 'productID',
            key: 'productID',
            width: 60,
            align: 'center'
        },
        {
            title: '商品图片',
            dataIndex: 'productUrl',
            key: 'productUrl',
            align: 'center',
            width: 120
        },
        {
            title: '商品名称',
            dataIndex: 'productName',
            key: 'productName',
            align: 'center',
        },
        {
            title: '货号',
            dataIndex: 'productID',
            key: 'productID',
            align: 'center',
            width: 120
        },
        {
            title: '价格',
            dataIndex: 'productPrice',
            key: 'productPrice',
            align: 'center',
            width: 120
        },
        {
            title: '分类',
            dataIndex: 'productClassify1',
            key: 'productClassify1',
            align: 'center',
        },
        {
            title: '品牌',
            dataIndex: 'productBrand',
            key: 'productBrand',
            align: 'center',
        },
        {
            title: '库存',
            dataIndex: 'productNum',
            key: 'productNum',
            align: 'center',
        },
        {
            title: '操作',
            key: 'action',
            align: 'center',
            width: 160,
            render: (_, record) => (
                <Space size="middle">
                    <a onClick={() => { add(record) }}>添加</a>
                </Space>
            ),
        },
    ];
    const [data, setData] = useState([])
    setListData = setData


    //点击添加
    const add = (val) => {
        console.log(val);
        dataId = val.productID
        promptBoxMethod(true)
    }

    // 选择的数组
    const rowSelection = {
        onChange: (selectedRowKeys, selectedRows) => {
            console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
        },
        getCheckboxProps: (record) => ({
            disabled: record.name === 'Disabled User',
            // Column configuration not to be checked
            name: record.name,
        }),
    };
    // //跳转页面
    // const { getCount } = father;
    // const gotoCommodityHome = () => {
    //     const value = 2
    //     console.log('重新加载promotionHome');
    //     getCount(value);
    // };

    return (
        <Table rowSelection={{
            type: 'checkbox',
            ...rowSelection,
        }}
            columns={columns}
            dataSource={data}
            pagination={{
                pageSize: 4
            }} />
    )
};


const addCommodity = (props) => {
    store = useContext(mycontext)
    const promotionIdData = store.promotionProductIdObj.promotionId;
    const [isModalOpen, setIsModalOpen] = useState(false);
    promptBox = isModalOpen;
    promptBoxMethod = setIsModalOpen
    const { token } = theme.useToken();
    const listStyle = {
        textAlign: 'center',
        background: token.colorFillAlter,
        borderRadius: token.borderRadiusLG,
        marginTop: 16,
    };
    const handleChange = (value) => {
        console.log(`selected ${value}`);
    };
    const [selectionType, setSelectionType] = useState('checkbox');

    //模态框
    const handleOk = () => {
        const id = {
            promotionId: promotionIdData,
            productID: dataId,
        }
        http({
            url: '/promotion/addProductData',
            method: 'post',
            data: id
        }).then(res => {
            console.log(res);
            if (res.code === 200) {
                message.success('数据添加成功');
            }
        }).catch(() => {
            message.error('请求错误');
        })
        setIsModalOpen(false);
    };
    const handleCancel = () => {
        message.success('取消删除');
        setIsModalOpen(false);
    };

    //跳转添加促销页面
    father = props
    const { getCount } = props;
    const goBack = () => {
        const value = 2
        console.log('重新加载addPromotion');
        getCount(value);
    };
    return (
        <div className='addCommodityBOx'>
            <AdvancedSearchForm />
            <div style={listStyle}>
                <div style={{ lineHeight: '2rem', display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', height: '2rem', padding: '1rem' }}>
                    <h3>数据列表</h3>
                    <div>
                        <Button
                            className='goBackBtn'
                            onClick={goBack}
                        >
                            返回
                        </Button>
                        <Select
                            defaultValue="批量操作"
                            onChange={handleChange}
                            options={[
                                { value: 'jack', label: '批量删除' },
                                { value: 'lucy', label: '批量XX' },
                            ]}
                        />
                    </div>
                </div>

                <div style={{ lineHeight: '20rem', }}>
                    <Divider />
                    <TableDetail />
                </div>
            </div>
            <Modal
                title="添加确定"
                open={isModalOpen}
                onOk={handleOk}
                onCancel={handleCancel}
                okText={'确定'} cancelText={'取消'}>
                <h3>确定要添加吗？</h3>
            </Modal>
        </div>
    );
}

export default addCommodity;